package org.aom.litebean;

import java.awt.Graphics;
import java.io.IOException;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aom.service.base.JCaptchaException;
import org.aom.util.FaceUtil;
import org.aom.util.Util;
import org.operamasks.faces.annotation.Action;
import org.operamasks.faces.annotation.AfterRender;
import org.operamasks.faces.annotation.BeforeRender;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.LocalString;
import org.operamasks.faces.annotation.ManagedBean;
import org.operamasks.faces.annotation.ManagedBeanScope;
import org.operamasks.faces.annotation.Required;
import org.operamasks.faces.component.html.impl.UIIFrame;
import org.operamasks.faces.component.layout.impl.UIWindow;
import org.operamasks.faces.component.widget.UIDrawImage;
import org.springframework.security.AccountExpiredException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.concurrent.ConcurrentLoginException;
import org.springframework.security.ui.AbstractProcessingFilter;
import org.springframework.stereotype.Component;

/**
 * 登陆页面托管Bean
 * 
 * @author Saya
 */
@Component
@ManagedBean(name = "loginBean", scope = ManagedBeanScope.REQUEST)
public class LoginBean {

	/**
	 * 国际化资源串
	 */
	@LocalString
	private Map<String, String> messages;

	/**
	 * 登陆名称
	 */
	@SuppressWarnings("unused")
	@Required(message = "#{this.messages.nameIsRequired}")
	@Bind(id = "j_username", attribute = "value")
	private String j_username;

	/**
	 * 登陆密码
	 */
	@SuppressWarnings("unused")
	@Required(message = "#{this.messages.pwdIsRequired}")
	@Bind(id = "j_password", attribute = "value")
	private String j_password;

	@SuppressWarnings("unused")
	@Required(message = "#{this.messages.validateCodeIsRequired}")
	@Bind(id = "j_captcha", attribute = "value")
	private String j_captcha;

	@Bind(id = "OperationDialog", attribute = "binding")
	protected UIWindow OperationDialog;

	@Bind(id = "OperationFrame", attribute = "binding")
	protected UIIFrame OperationFrame;

	/**
	 * 登陆提示
	 */
	@SuppressWarnings("unused")
	@Bind(id = "tips", attribute = "value")
	private String tips;

	@Bind(id = "jcaptchaImg", attribute = "binding")
	private UIDrawImage jcaptchaImg;

	@Action(id = "loginBtn")
	public void loginBtn() {
		ServletContext servletContext = (ServletContext) FacesContext
				.getCurrentInstance().getExternalContext().getContext();
		HttpServletRequest request = (HttpServletRequest) FacesContext
				.getCurrentInstance().getExternalContext().getRequest();
		HttpServletResponse respone = (HttpServletResponse) FacesContext
				.getCurrentInstance().getExternalContext().getResponse();
		RequestDispatcher rd = servletContext
				.getRequestDispatcher("/j_spring_security_check");
		try {
			rd.forward(request, respone);
		} catch (ServletException e) {
		} catch (IOException e) {
		} finally {
			FacesContext.getCurrentInstance().responseComplete();
		}
	}

	@Action(id = "resetBtn", immediate = true)
	public void resetBtn() {
		j_username = "";
		j_password = "";
		j_captcha = "";
	}

	public void draw(Graphics g, int width, int height) {
	}

	private void createValidateCode() {
		String randCode = Util.getRandom(5);
		jcaptchaImg.setValue("/security/jcaptcha.jpg?" + randCode);
	}

	@Action(id = "jcaptchaImg", event = "onclick", immediate = true)
	public void reGenernateCaptchaImage() throws IOException {
		createValidateCode();
		jcaptchaImg.refresh();
	}

	@Action(id = "changeImg", immediate = true)
	public void changeImage() {
		try {
			reGenernateCaptchaImage();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Action(id = "findpw", immediate = true, event = "onclick")
	public void findpw() {
		OperationFrame.load("fontservice/findpw/findpw.faces");
		OperationDialog.setWidth(400);
		OperationDialog.setHeight(400);
		OperationDialog.show();
	}

	@AfterRender
	public void afterRender() {
		tips = null;
	}

	@BeforeRender
	public void beforeRender(boolean isPostback) {
		resetBtn();
		Exception exc = (Exception) FaceUtil.getSessionMap().get(
				AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY);
		if (exc != null) {
			try {
				reGenernateCaptchaImage();
			} catch (Exception e) {
			}
			if (exc instanceof BadCredentialsException) {
				tips = messages.get("LoginBean.tips.nouser");
			} else if (exc instanceof JCaptchaException) {
				tips = messages.get("LoginBean.tips.validateCodeWrong");
			} else if (exc instanceof ConcurrentLoginException) {
				tips = messages.get("LoginBean.tips.overMax");
			} else if (exc instanceof AccountExpiredException) {
				tips = messages.get("LoginBean.tips.overTime");
			}
		}
	}
}
